<template>
  <div v-if="!printShow">
    <div class="front">
      <el-collapse v-model="activeNames" class="front-collapse"
        @change="activeNames = !activeNames; collapseName == '收起' ? collapseName = '展开' : collapseName = '收起'">
        <el-collapse-item :title="collapseName" class="collapse-1" name="1">
          <el-form :model="searchForm" label-width="120px">
            <el-form-item label="条码号" class="front-input">
              <el-input v-model="searchForm.checkBoundCode" />
            </el-form-item>
            <el-form-item label="调整单id" class="front-input">
              <el-input v-model="searchForm.checkName" />
            </el-form-item>
            <el-form-item label="调整人员id" class="front-input">
              <el-input v-model="searchForm.warehouseId" />
            </el-form-item>
            <el-form-item label="调整人员id" class="front-input">
              <el-input v-model="searchForm.storageId" />
            </el-form-item>
            <el-form-item label="调整人员id" class="front-input">
              <el-input v-model="searchForm.remark" />
            </el-form-item>
            <el-form-item label="调整人员id" class="front-input">
              <div class="block">
                <el-date-picker
                  v-model="timeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期时间范围"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
<!-- 引入 create.vue 组件 -->
<create-vue @createdSuccessfully="handleCreatedSuccessfully"></create-vue>
    <div class="tail">
      <div class="tail-action">
        <el-button 
          type="primary" 
          plain
          icon="Plus"
          size="mini" 
          @click="handleAdd"
          >添加盘点单</el-button>
        <el-button type="primary">导出明细</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" :max-height="collapseName == '收起' ? 450 : 660" v-loading="tableLoading" @selection-change="handleChangeSelection">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column type="selection" width="40" />
        <el-table-column v-for="item in inboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
          :max-width="item.maxWidth" :label="item.label">
          <!-- <template v-if="true" v-slot:default="scope">
            <div v-if="item.prop == 'orderType'">
              <el-tag v-if="scope.row[item.prop] == 0" type="success">采购入库</el-tag>
              <el-tag v-else-if="scope.row[item.prop] == 1" type="info">借货入库</el-tag>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template> -->
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.status==='0'" link type="primary" size="small" @click="check(scope.row)">继续盘点</el-button>
            <el-button v-else link type="danger" size="small" @click="check(scope.row)">查看明细</el-button>
            <el-button link type="primary" size="small" @click="openEditRemarkDialog(scope.row)">编辑备注</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="float: right; margin-top: 15px;">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" v-model:total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
  </div>
  <div v-else>
    <a-button @click="printShow = false" type="primary" danger>退出打印页面</a-button>
    <print :provider="providerData" :printData="printDataProp"></print>
  </div>

  <el-dialog v-model="dialogVisible2" title="编辑备注" width="30%" :close-on-click-modal="true">
  <!-- 编辑备注的输入框 -->
  <el-input v-model="editRemark" placeholder="请输入备注"></el-input>
  
  <span slot="footer" class="dialog-footer">
    <el-button class="remarkbutton" type="primary" @click="confirmUpdate">确 定</el-button>
    <el-button class="remarkbutton" @click="closeDialog">取 消</el-button>
  </span>
</el-dialog>
</template>
    
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { getcheckOrder } from '@/api/inbound/inbound'
import { updateCheckRemark } from '@/api/auth/auth';
import { getWarehouseListV2 } from '@/api/setting/setting';
import { getSupplierList } from "@/api/user/user"
import { List } from '@element-plus/icons-vue';
import { useRoute, useRouter } from "vue-router"
import { useStore } from 'vuex';
import axios from 'axios';
export default defineComponent({
  name: "checkList",
  components: {
    List
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    
   
  
   
    const timeRange = ref([])// 时间选择器
   
    const drawer = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)//显示设置是否全选
    const searchForm = reactive({  //入库查询表单数据
      checkBoundCode: null,
      checkName: null,
      warehouseId: null,
      storageId: null,
      remark: null,
      startTime: null,
      endTime: null
    })
    const inboundJadeData = ref([])
    const selectedFilters = ref([])
    const selectedRows = ref([])//已勾选记录
    const inboundDataColumn = ref([])//表头数据
    const supplierList = ref([])
    const warehouseList = ref([])
    const tableFilter = ref([
      // "warehouseStorageList": [
      //     {
      //         "warehouseId": 71,
      //         "warehouseName": "肇庆仓",
      //         "storageId": 85,
      //         "storageName": "肇庆仓-默认仓位"
      //     }
      // ],
      { label: 'id', prop: 'id', width: '100', isdisabled: true, isSelected: true },
      { label: '盘点单编码', prop: 'orderCode', width: '100', isdisabled: true, isSelected: true },
      { label: '盘点单名字', prop: 'orderName', width: '100', isdisabled: true, isSelected: true },
      { label: '备注', prop: 'remark', width: '200', isdisabled: true, isSelected: true },
      { label: '入库人员', prop: 'createBy', width: '100', isdisabled: true, isSelected: true },
      { label: '入库时间', prop: 'createTime', width: '200', isdisabled: true, isSelected: true },
      { label: '结束盘点时间', prop: 'endTime', width: '200', isdisabled: true, isSelected: true },
      { label: 'checkResult', prop: 'checkResult', width: '200', isdisabled: true, isSelected: true },
      { label: 'status', prop: 'status', width: '200', isdisabled: true, isSelected: true },
    ])

    const collapseName = ref('展开');
    const activeNames = ref(false)

    //分页处理
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: inboundJadeData.value.length,
      }
    });

    // loading
    const tableLoading = ref(true)
    const tableData = () => {
      // console.log("inboundJadeData:",inboundJadeData)
      return inboundJadeData.value
    };
    const handleCurrentChange = (e) => {//改变页码
      state.data.page = e;
      handleGetInboundOrderList(e, state.data.limit)
    };
    const handleSizeChange = (e) => {//改变页数限制
      state.data.limit = e;
      handleGetInboundOrderList(state.data.page, e)
    };

    const handleGetInboundOrderList = (page, limit) => {//获取入库单列表
      tableLoading.value = true
      const params = {
        pageNum: page,
        pageSize: limit,
        checkBoundCode: null,
        checkName: null,
        warehouseId: null,
        storageId: null,
        remark: null,
        startTime: null,
        endTime: null
      }
      console.log(params)
      getcheckOrder(params).then((res) => {
        console.log("getcheckOrder:",res)
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
      tableLoading.value = false
    }
    const handleCheckAllChange = (val) => {//全选按钮
      inboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }
    const handleCheckChange = (val) => {//勾选列
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inboundDataColumn.value = temp
      selectedFilters.value = inboundDataColumn.value.map(item => item.label)
    }

    /** 新增按钮操作 */
    const handleAdd = async() => {
      // 创建新的路由配置
      const newRoute = {
        path: '/checklist/create',
        name: 'StartCheck',
        component: () => import('@/views/inbound/checklist/create.vue'),
        meta: {
          keepAlive: true,
          title: "新增盘点",
          isDynamic: true, // 添加标志
        } 
      };
      // 添加路由到路由器
      router.addRoute(newRoute);
      const newTag = {
        path: '/checklist/create',
        title: '新增盘点'
      };
      router.push({ path: newTag.path});
      store.commit('addTag', newTag);
    }

    /** 查看盘点操作 */
    const check = async(value) => {
      // console.log("value:",value)
      const newRoute = {
        path: '/checklist/edit',
        name: 'CheckEdit',
        component: () => import('@/views/inbound/checklist/edit.vue'),
        meta: {
          keepAlive: true,
          title: "查看盘点",
          isDynamic: true,
          query: value
        } 
      };
      // 添加路由到路由器
      router.addRoute(newRoute);
      const newTag = {
        path: '/checklist/edit',
        title: '查看盘点',
        query: value
      };
      // 跳转并传递查询参数
      // router.push({ path: newTag.path, query: { id: 123, name: 'test' } });
      router.push({ path: newTag.path, query: value});
      store.commit('addTag', newTag);
      
    }

    onBeforeMount(() => {
      getSupplierList().then((res) => {
        supplierList.value = res.rows
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res
      })
      handleGetInboundOrderList(state.data.page, state.data.limit)
    })

    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inboundDataColumn.value.push(item)
        }
      })
    })
    const mergeOrder = () => {

    }
    const onSearch = () => {
      const params = {
        pageSize: state.data.limit,
        pageNum: state.data.page,
        checkBoundCode: searchForm.checkBoundCode,
        checkName: searchForm.checkName,
        warehouseId: searchForm.warehouseId,
        storageId: searchForm.storageId,
        remark: searchForm.remark,
        startTime: timeRange.value[0]||null,
        endTime: timeRange.value[1]||null
      }
      console.log(params)
      getcheckOrder(params).then((res) => {
        console.log("getcheckOrder:",res)
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }

    const openDetails = (row) => { //删除仓位
      drawer.value = true
      rowDetails.value = row
    }
    const handleChangeSelection = (selection) => {//已勾选的记录
      selectedRows.value = selection
      // console.log(selectedRows)
      // createElementTypes(selectedRows._rawValue)
      // console.log(printData)
    }
    const onReset=()=>{
      searchForm.checkOrderId=searchForm.barcode=searchForm.createById=searchForm.startTime=null
    }


//编辑备注
const editRemark = ref('');
    const dialogVisible2 = ref(false);
    const rowDetails = ref({});
    const checkOrderIdValue = ref(null);

    const openEditRemarkDialog = (row) => {
      rowDetails.value = row;
      dialogVisible2.value = true;
      editRemark.value = row.remark;
      checkOrderIdValue.value = row.id;
    };

    const closeDialog = () => {
      dialogVisible2.value = false;
    };

    const confirmUpdate = () => {
      if (!rowDetails.value ||!checkOrderIdValue.value || editRemark.value.trim() === '') {
        ElMessage.error('缺少有效的数据来更新备注');
        return;
      }

      const params = {
        checkOrderId: Number(checkOrderIdValue.value),
        remark: editRemark.value.trim(),
      };
      console.log('准备发送给后端的参数：', params);
      updateCheckRemark(params).then(response => {
        // 成功处理
        ElMessage.success('编辑备注成功');
        dialogVisible2.value = false;
        // 更新前端页面的备注值
        rowDetails.value.remark = editRemark.value;
      }).catch((error) => {
        console.error('更新备注失败：', error.response);
        ElMessage.error('修改备注失败，请重试');
      });
    };

    return {
      editRemark,
      rowDetails,
      dialogVisible2,
      
      openEditRemarkDialog,
      closeDialog,
      
      confirmUpdate,
      inboundJadeData,editRemark, 
      searchForm, rowDetails, drawer, dialogVisible2,closeDialog,
      collapseName, warehouseList, supplierList,confirmUpdate,openEditRemarkDialog,
      activeNames,timeRange,
      inboundDataColumn, selectedFilters, tableFilter, checkAll, isIndeterminate,
      tableData, mergeOrder, openDetails, handleChangeSelection,
      handleCurrentChange, handleSizeChange, handleCheckAllChange, handleCheckChange,
      handleGetInboundOrderList, onSearch,onReset,tableLoading,handleAdd,check,
      ...toRefs(state),
    };
  },
});


</script>
    #F8F8F8
    
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #FFF;
  padding: 10px;

  .front-input {
    width: 320px;
  }
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
  margin-top: 10px;
  padding: 10px;
}

.tail-action {
  display: flex;
  margin-bottom: 10px;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}
</style>
    